package controller;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import model.Teacher;
import model.User;

/**
 * Created by BaiYunfei on 2017/6/14.
 */
public class TeacherController extends BaseController {
    public void list(){
        Page<Teacher> teacherPage = Teacher.dao.paginate(getPageNumber(),getPageSize(),"SELECT *", "FROM Teacher");
        renderDataTable(teacherPage);
    }

    @Before(Tx.class)
    public void save(){
        Teacher teacher = getModel(Teacher.class,"");
        if(Teacher.dao.findById(teacher.getStr("Teacher_ID")) != null){
            teacher.update();
        }
        
        User user = new User();
        user.setId(User.dao.generateId());
        user.setUsername(teacher.getStr("Teacher_ID"));
        user.setPassword(teacher.getStr("Teacher_ID"));
        user.save();
        
        teacher.set("ID", user.getLong("ID"));
        teacher.save();
        setAttr("status","success");
        renderJson();
    }
    
    public void remove(){
    	String id = getPara("id");
    	Teacher.dao.deleteById(id);
    	renderJson();
    }
    
    public void addPage(){
    	if(isParaExists("id")){
    		String id = getPara("id");
    		Teacher stu  = Teacher.dao.findById(id);
    		setAttr("teacher",stu);
    	}
        render("teacher-add.html");
    }

    public void index(){
        render("teacher-list.html");
    }

}
